package com.database;

import java.sql.*;

public class CoursesDB extends Database
{
	int courseNumber;
	String courseName = null;
	
	
	public AdministratorDB()
	{
		tableName = "Courses";
	}
	
	public CoursesDB(int courseNumber, String courseName)
	{
		tableName = "Courses";
		
		this.courseNumber = courseNumber;
		this.courseName = courseName;
	}
	
    //@assignable stmt,sqlString;
	//@signals_only RuntimeException, IOException, SQLException;
	public boolean UserExists(int id) throws SQLException
	{
		Statement stmt = connection.createStatement();
		String sqlString = "select * from " + tableName + " where courseNumber = " + id;
		
		ResultSet rs = stmt.executeQuery(sqlString);
		
		if (rs.next())//check if user exists in databse
		{
			this.courseNumber = Integer.parseInt(rs.getString("courseNumber"));
			this.courseName = rs.getString("coursename");
			return true;
		}
		else
		{
			return false;
		}
	}
	
	//@requires courseName !== Null;
    //@assignable newCoursename,courseNumber;
	//@signals_only RuntimeException, IOException,SQLException;
	public void ModFirstName(String newCourseName, int tupleID) throws SQLException
	{
		super.Modify(newCourseName, "courseName","courseNumber",tupleID); 
	}
	
    //@assignable stmt,sqlString;
	//@signals_only RuntimeException, IOException,SQLException;
	@Override
	public void Insert() throws SQLException 
	{
		Statement stmt = connection.createStatement();
				
	    String sqlString = "INSERT INTO " + tableName + " VALUES (" + 
	    					courseNumber + ", " +
	    					AddQuotes(courseName) + ", " +
	    					")";
	    
	    stmt.executeUpdate(sqlString);
	        
	    System.out.println(sqlString + " complete");
	}
	
	@Override
    //@assignable stmt,id,sqlString;
	//@signals_only RuntimeException, IOException,SQLException;
	public void Delete(String primaryKey) throws SQLException 
	{
		Statement stmt = connection.createStatement();
		int id = Integer.parseInt(primaryKey);
		String sqlString = "DELETE from " + tableName + " WHERE courseNumber = " + id;
		stmt.executeUpdate(sqlString);
		System.out.println(sqlString + " complete");
	}
	
	@Override
    //@assignable sqlString, stmt, ResultSet;
	//@signals_only RuntimeException, IOException,SQLException;
	public void Display() throws SQLException 
	{
	    String sqlString = "SELECT * FROM " + tableName;
	    Statement stmt = connection.createStatement();

	    ResultSet rs = stmt.executeQuery(sqlString);

	    while (rs.next())
	    {
	        System.out.println
	        (
	            rs.getString("courseNumber") + " " +
	            rs.getString("courseName") + " " 
	        );
	    }	
	}

}
